package com.guoyh.bilui.basecustomview

import android.content.Context
import androidx.databinding.ViewDataBinding
import android.widget.LinearLayout
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.databinding.DataBindingUtil

abstract class BaseCustomView<DB : ViewDataBinding, VM : BaseCustomViewModel>(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
    defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes),
    ICustomView<VM> {

    protected lateinit var mBinding: DB
    protected lateinit var viewModel: VM
    protected var isCanClick: Boolean = true

    var mListener: ICustomViewActionListener<VM>? = null


    override fun getRootView() = mBinding.root

    init {
        val inflater =
            this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        if (setViewLayoutId() != 0) {
            mBinding = DataBindingUtil.inflate(inflater, setViewLayoutId(), this, false)
            if (isCanClick) {
                mBinding.root.setOnClickListener { view ->
                    if (mListener != null) {
                        mListener!!.onAction(
                            ICustomViewActionListener.ACTION_ROOT_VIEW_CLICKED,
                            view,
                            viewModel
                        )
                    }
                    onRootClick(view)
                }
            }
            this.addView(mBinding.root)
            toInitUi()
        }
    }

    protected open fun toInitUi() {}

    override fun setData(data: VM) {
        viewModel = data
        setDataToView(viewModel)
        mBinding.executePendingBindings()
    }


    protected abstract fun setViewLayoutId(): Int
    protected abstract fun setDataToView(data: VM)
    protected abstract fun onRootClick(view: View)

}